package com.ean.backpack.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.ean.backpack.domain.Role;
import com.ean.backpack.domain.User;
import com.ean.backpack.repository.RoleRepository;
import com.ean.backpack.repository.UserRepository;

/**
 * Data initialization service
 *
 * @author valentin
 *
 */
@Service("initDataService")
public class InitDataService {

	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(InitDataService.class);

	@Autowired
	UserRepository userRepository;

	@Autowired
	RoleRepository roleRepository;

	private PasswordEncoder encoder = new Md5PasswordEncoder();

	public void init() {
		if(userRepository.findByEmail("admin@mail.com") != null){
			return;
		}
		/* A user with administrator right */
		Role adminRole = getRole("ROLE_ADMIN");
		Role userRole = getRole("ROLE_USER");

		User admin = new User();
		admin.setFirstName("AdminF");
		admin.setLastName("AdminL");
		admin.setEmail("admin@mail.com");
		admin.setPassword(encoder.encodePassword("admin", null));
		admin.setIsEnabled(true);
		this.userRepository.save(admin);
		admin.getRoles().add(adminRole);
		admin.getRoles().add(userRole);
		this.userRepository.save(admin);

		/* A user with no administrator right */
		User user = new User();
		user.setFirstName("UserF");
		user.setLastName("UserL");
		user.setEmail("user@mail.com");
		user.setPassword(encoder.encodePassword("user", null));
		user.setIsEnabled(true);
		this.userRepository.save(user);
		user.getRoles().add(userRole);
		this.userRepository.save(user);

		// add 100 more users without roles (To test pagination)
		List<User> listUsers = new ArrayList<User>();
		User newUser;
		for (int i = 0; i < 100; i++) {
			newUser = new User();
			newUser.setFirstName("FirstName_" + i);
			newUser.setLastName("LastName_" + i);
			newUser.setEmail("User_" + i + "@mail.com");
			newUser.setPassword(encoder.encodePassword("user", null));
			newUser.setIsEnabled(true);
			listUsers.add(newUser);
		}
		this.userRepository.save(listUsers);
	}

	private Role getRole(final String roleId) {
		Role result = roleRepository.findByRoleName(roleId);
		if (result == null) {
			result = new Role();
			result.setRoleName(roleId);
			roleRepository.save(result);
		}
		return result;
	}
}
